package com.tensuqare.user.controller;

import com.tensuqare.user.pojo.Admin;
import com.tensuqare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;


    //新增管理员
    @PostMapping()
    public Result addAdmin(@RequestBody Admin admin) {
        System.out.println("admin = " + admin);
        try {
            adminService.addAdmin(admin);
            return new Result(true, StatusCode.OK, "新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.OK, "新增失败");
        }
    }

    //管理员登陆密码校验
    @PostMapping("login")
    public Result loginAdmin(@RequestBody Admin admin) {

        Admin admin1 = adminService.login(admin);
        System.out.println("admin1 = " + admin1);
        //对管理员用户生成token（添加签权）
        //1.生成token数据
        String token = jwtUtil.createJWT(admin1.getId(), admin.getLoginname(), "admin");
        System.out.println("token = " + token);
        Map map = new HashMap();
        map.put("token", token);
        map.put("name", admin.getLoginname());
        if (admin1 != null) {
            return new Result(true, StatusCode.OK, "登录成功", map);
        }
        return new Result(false, StatusCode.OK, "登录失败");

    }

    //删除管理员
    @DeleteMapping("{adminId}")
    public Result deleteAdmin(@PathVariable String adminId) {
        //判断此用户是否有权限...(拦截器中处理)
        //1.从request中取出admin_roles这个key对应的值
        Claims claims = (Claims) request.getAttribute("admin");
        if (claims != null) {
            adminService.deleteAdmin(adminId);
            return new Result(true, StatusCode.OK, "删除成功");
        } else {
            return new Result(false, StatusCode.OK, "删除失败");
        }

    }
}
